<?php
require_once dirname(__FILE__) . '/../common/common.inc.php';
require_once dirname(__FILE__) . "/../database/$database/database.inc.php";
require_once dirname(__FILE__) . '/../common/_utils.class.php';

header('Content-Type: text/plain');

global $myManager;

$action = MiscUtils::decryptParam('action', NULL);

$myManager->start_t();
try {
  switch ($action) {
    case 'login':
      login($myManager);
      break;
    case 'register':
      register($myManager);
      break;
    case 'create':
      create($myManager);
      break;
    case 'alter':
      alter($myManager);
      break;
    case 'delete':
      delete($myManager);
      break;
    case 'uploadFile':
      uploadFile($myManager);
      break;
    case 'copyFile':
      copyFile($myManager);
      break;
    case 'downloadFile':
      downloadFile($myManager);
      break;
    case 'retrieveFileRoot':
      retrieveFileRoot($myManager);
      break;
    default:
      break;
  }
} catch (PDOException $e) {
  echo MiscUtils::encode($e->getMessage());
}
$myManager->commit_t();

function login($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  
  $orm = classToOrm('customer');
  $result = $orm->find($myManager, NULL, NULL, NULL, NULL, "d.account = '$args->account' AND d.password = '$args->password'", NULL);
  if (count($result->data) == 1) {
    $customer = $result->data[0];
    
    $_SESSION[OPERATOR] = $customer;
    setcookie(OPERATOR, json_encode($customer), (time() + 3600), PATH, DOMAIN);
    
    $dir = '../' . UPDIR . $customer->account;
    if (!file_exists($dir)) {
      mkdir($dir, 0777);
    }
    
    echo MiscUtils::encode(array());
  } else {
    echo 'INCORRECT ACCOUNT OR PASSWORD';
  }
}

function register($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  $orm = classToOrm('customer');
  $account = $args->customer->account;
  $result = $orm->find($myManager, NULL, NULL, NULL, NULL, 'd.account =\''. $account . '\'', NULL);
  if (count($result->data) != 0) {
    echo 'Account exists!';
  } else {
    $epCustomer = $orm->add($myManager, $args->customer);
    
    $myManager->commit_t();
    $myManager->start_t();
  
    $customer = $orm->__toObject($myManager, $epCustomer, new stdClass()); 
    
    $_SESSION[OPERATOR] = $customer;
    setcookie(OPERATOR, json_encode($customer), (time() + 3600), PATH, DOMAIN);
    
    if (!file_exists('../' . UPDIR)) {
      die('NO ROOT FOLDER');
    }
    
    $dir = '../' . UPDIR . $customer->account;
    if (!file_exists($dir)) {
      mkdir($dir, 0777);
    }
    
    echo MiscUtils::encode($customer);
  }
}

function create($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  $file = $args->file;
  
  $dir = '../' . UPDIR . $_SESSION[OPERATOR]->account . '/';
  if (!file_exists($dir)) {
    die('NO ACCOUNT FOLDER');
  }
  
  $orm = classToOrm('file');
  if (!$file->dirId) {
    $fp = fopen($dir . $file->trueName, 'w') or die('CAN NOT OPEN FILE');
    fclose($fp);
  }
  $orm->add($myManager, $file);
  echo MiscUtils::encode(array());
}

function alter($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  
  $file = $args->file;
  $name = $args->name;
  
  $dir = '../' . UPDIR . $_SESSION[OPERATOR]->account . '/';
  if (!file_exists($dir)) {
    die('NO ACCOUNT FOLDER');
  }
  
//  $extend = pathinfo($file->name);
//  $extend = '.' . strtolower($extend["extension"]);
//  $alertName = $name . $extend;
  
  if (!$file->dirId && file_exists($dir . $file->name)) {
    rename($dir . $file->name, $dir . $name);
  }
  
  $orm = classToOrm('file');
  
  $file->name = $name;
  $orm->update($myManager, $file);
  echo MiscUtils::encode(array());
}

function delete($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  $files = $args->files;

  $dir = '../' . UPDIR . $_SESSION[OPERATOR]->account . '/';
  if (!file_exists($dir)) {
    die('NO ACCOUNT FOLDER');
  }
  
  $orm = classToOrm('file');
  foreach ($files as &$file) {
    if (!$file->dirId) {
      unlink($dir . $file->trueName);
    } else {
      $root = new stdClass();
      $root->root = array();
      __expandFileSub($myManager, $file->dirId, $file->customerTrackId, $root);
      $result = $root->root;
      
      foreach ($result as &$res) {
        if (!$res->dirId) {
          unlink($dir . $res->trueName);
        }
        $orm->remove($myManager, $res);
      }
    }
    $orm->remove($myManager, $file);
  }
  echo MiscUtils::encode(array());
}

function uploadFile($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  $file = $args->file;
  
  $orm = classToOrm('file');
  $eFile = $orm->update($myManager, $file);
  
  $myManager->commit_t();
  $myManager->start_t();

  $file = $orm->__toObject($myManager, $eFile, new stdClass()); 
  echo MiscUtils::encode($file);
}

function copyFile($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  $files = $args->files;

  $dir = '../' . UPDIR . $_SESSION[OPERATOR]->account . '/';
  if (!file_exists($dir)) {
    die('NO ACCOUNT FOLDER');
  }
  
  $orm = classToOrm('file');
  foreach ($files as &$file) {
    if (!$file->dirId) {
      $fp = fopen($dir . $file->trueName, 'w+') or die('CAN NOT OPEN FILE');
      fclose($fp);
    } else {
      $root = new stdClass();
      $root->root = array();
      __expandFileSub($myManager, $file->dirId, $file->customerTrackId, $root);
      $result = $root->root;
      
      $arr = new stdClass();
      $arr->arr = array();
      $arr->rs = array();
      __expandFile($result, $file, $arr, $file->dirId);

      $used = $arr->rs;
      if (count($used) != 0) {
        for ($j = 0, $jl = count($used); $j < $jl; $j++) {
          $a = $used[$j];
          if (!$a->dirId) {
            continue;
          }
          __expandFile($used, $a, $arr, $a->dirId);
        }
      }
      
      $copy = $arr->arr;
      foreach ($copy as &$cy) {
        if (!$cy->dirId) {
          $fp = fopen($dir . $cy->trueName, 'w+') or die('CAN NOT OPEN FILE');
          fclose($fp);
        }
        $orm->add($myManager, $cy);
      }
    }
    $orm->add($myManager, $file);
  }
  echo MiscUtils::encode(array());
}

function downloadFile($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  $file = $args->file;
  
  $file->downloaded = $file->downloaded + 1;
  
  $orm = classToOrm('file');
  $eFile = $orm->update($myManager, $file);
  
  $myManager->commit_t();
  $myManager->start_t();

  $file = $orm->__toObject($myManager, $eFile, new stdClass()); 
  echo MiscUtils::encode($file);
}

function retrieveFileRoot($myManager) {
  $args = json_decode(MiscUtils::decryptParam('a', '[]'));
  
  $dirId = $args->dirId;
  $cTrackId = $args->customerTrackId;
  
  $orm = classToOrm('file');
  $root = new stdClass();
  $root->root = array();
  __expandFileNode($myManager, $dirId, $cTrackId, $root);
  $result = $root->root;
  echo MiscUtils::encode($result);
}

function __expandFileNode($myManager, $dirId, $cTrackId, $root) {
  $orm = classToOrm('file');
  $result = $orm->find($myManager, NULL, NULL, NULL, NULL, "d.dirId = '$dirId' AND d.customerTrackId = '$cTrackId'", NULL);
  $parent = $result->data;
  foreach($parent as $part) {
    $root->root[] = $part;
    __expandFileNode($myManager, $part->parentDirId, $cTrackId, $root);
  }
}


function __expandFileSub($myManager, $dirId, $cTrackId, $root) {
  $orm = classToOrm('file');
  $result = $orm->find($myManager, NULL, NULL, NULL, NULL, "d.parentDirId = '$dirId' AND d.customerTrackId = '$cTrackId'", NULL);

  $parent = $result->data;
  foreach($parent as $part) {
    $root->root[] = $part;
    __expandFileSub($myManager, $part->dirId, $cTrackId, $root);
  }
}

function __expandFile($result, $parent, $arr, $dirId) {
  $arr->rs = array();
  $parent->dirId = Utils::unique();
  for ($i = 0, $il = count($result); $i < $il; $i++) {
    $res = $result[$i];
    if ($res->parentDirId == $dirId) {
      if (!$res->dirId) {
         $res->parentDirId = $parent->dirId;
         $type = explode('.', $res->name);
         $res->trueName = Utils::unique() . '.' . $type[count($type) - 1];
      } else {
        $arr->rs[] = $res;
        $res->parentDirId = $parent->dirId;
      }
     $arr->arr[] = $res;
    } else {
      $arr->rs[] = $res;
    }
  }
}
?>